# _*_ coding: utf-8 _*_
# @创建时间：2024/3/11 16:00
# @作者：dengqihua
# @名称 : logger.py
# @描述 : 日志初始化

import logging
import os
from logging.handlers import TimedRotatingFileHandler

from aiologger import Logger
from aiologger.formatters.base import Formatter
from aiologger.handlers.files import AsyncTimedRotatingFileHandler, RolloverInterval

from app.config.setting import settings

# 异步日志
aio_logger = Logger.with_default_handlers(name=settings.project_name)

# 同步日志
logger = logging.getLogger(name=settings.service_name)

# 项目根路径
root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 日志格式
log_format = "%(asctime)s - %(levelname)s - %(pathname)s:line=%(lineno)d;pid=%(process)d - %(message)s"


async def logger_init():
    # 初始化异步logger
    aio_handler = AsyncTimedRotatingFileHandler(
        filename=os.path.join(root_path, "logs", "log.log"),
        when=RolloverInterval.DAYS,
        interval=1,
        backup_count=30,
        encoding="utf-8",
    )
    aio_handler.formatter = AsyncFormatter(log_format)
    aio_logger.add_handler(aio_handler)

    # 初始化同步logger
    handler = TimedRotatingFileHandler(
        filename=os.path.join(root_path, "logs", "log.log"),
        when='D',
        interval=1,
        backupCount=30,
        encoding="utf-8"
    )
    handler.setFormatter(SyncFormatter(log_format))
    logger.addHandler(handler)


class BaseFormatter:
    def __init__(self, fmt=None, datefmt=None, style='%'):
        self._original_formatter = self._init_formatter(fmt, datefmt, style)
        self.root_path = root_path

    def _init_formatter(self, fmt, datefmt, style):
        raise NotImplementedError("子类必须实现这个方法以返回一个格式器实例。")

    def format(self, record):
        original_pathname = record.pathname
        try:
            if original_pathname.startswith(self.root_path):
                record.pathname = os.path.relpath(original_pathname, self.root_path)
            return self._original_formatter.format(record)
        finally:
            # 恢复原始的 pathname，以防其他 formatter 或输出需要它
            record.pathname = original_pathname


class AsyncFormatter(BaseFormatter, Formatter):
    def _init_formatter(self, fmt, datefmt, style):
        return Formatter(fmt=fmt, datefmt=datefmt, style=style)


class SyncFormatter(BaseFormatter, logging.Formatter):
    def _init_formatter(self, fmt, datefmt, style):
        return logging.Formatter(fmt=fmt, datefmt=datefmt, style=style)
